package com.boyaa.shells.tool 
{
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.text.TextField;
	import flash.utils.getQualifiedClassName;
	import flash.utils.getTimer;
	
	/**
	 * 帧频计算.
	 * new C5FPS().startCalc(stage);
	 */
	public class C5FPS 
	{
		
		/// 最后的时间.
		private var lastTime:uint;
		
		/// 经过了多少帧.
		private var framesPassed:uint = 0;
		
		/// 更新帧频的需要次数.
		private var resetAfter:uint = 15;
		
		/// 最后记录的FPS.
		private var fps:Number;
		
		/// 帧频输出框.
		private static var display:TextField;
		/// 鼠标坐标输出框
		private static var mouseTxt:TextField;
		/// 保留计算结果后几位.
		private var precision:uint = 2;
		
		/// The stage.
		private var stage:Stage;
		
		/**
		 * 开始计算FPS.
		 */
		public function startCalc(s:Stage):void
		{
			if (display == null)
			{
				lastTime = getTimer();
				framesPassed = 0;
				stage = s;
				
				
				var sprite:Sprite = new Sprite();
				sprite.graphics.beginFill(0 , 0.5);
				sprite.graphics.drawRoundRect(0 , 0, 110 , 40, 5);
				sprite.graphics.endFill();
				
				sprite.x = stage.stageWidth - 110;
				
				display = new TextField();
				display.width = 104;
				display.height = 19;
				display.textColor = 0xffffff;
				display.x = 55 / 2;
				
				sprite.addChild(display);
				
				mouseTxt = new TextField();
				mouseTxt.x = display.x;
				mouseTxt.textColor = 0xffffff;
				mouseTxt.y = display.y + 20;
				sprite.addChild(mouseTxt);
				
				stage.addEventListener(Event.ENTER_FRAME, update);
				stage.addEventListener(MouseEvent.CLICK, onClick);
				stage.addChild(sprite);
				sprite.y += 25;
				sprite.mouseEnabled = display.mouseEnabled = mouseTxt.mouseEnabled = false;
				
			}
		}
		
		private function onClick(e:MouseEvent):void 
		{
			var targetKey:String = getQualifiedClassName(e.target);			// 链接类
			var name:String = e.target.name;								// 实例名字
			//trace("<C5FPS> targetKey:" + targetKey, " 	targetName:" + name);
			//trace("-----------------------------------------------");
		}
		
		/**
		 * 停止计算帧频
		 */ 
		public function stopCalc():void
		{
			stage.removeEventListener(Event.ENTER_FRAME, update);
		}
		
		/**
		 * 计算帧频
		 */ 
		public function update(e:Event):void
		{
			framesPassed++;
			if (framesPassed == resetAfter) 
			{
				var t2:uint = getTimer();
				fps = ((1000 * framesPassed) / (t2 - lastTime));
				lastTime = t2;
				framesPassed = 0;
				if (display) 
				{
					display.text = ' fps:' + fps.toFixed(precision);
					mouseTxt.text = "x:" + stage.mouseX + ", " + "y:" + stage.mouseY;
				}
			}
		}
		
	}
}